<template>
  <el-drawer class="tl-drawer tl-drawer-approval" ref="drawerRef" :visible.sync="visible" :with-header="false" size="95%" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true" @open="open" @close="close" :destroy-on-close="true">
    <div class="approval-container">
      <el-tabs v-model="activeName" class="approval-tabs" lazy>
        <el-tab-pane label="任务信息" name="task">
          <labour-edit ref="taskInfoRef" :render="'div'" style="padding-right: 10px;" @hook:mounted="taskCreated"></labour-edit>
        </el-tab-pane>
        <el-tab-pane label="单据信息" name="doc" v-if="taskInfo.type === 0">
          <div class="form-main-area">
            <component v-if="!disabled" :is="subPage" ref="subPage" render="div" @hook:mounted="pageCreated" :visible.sync="visible" @close="visible = false"></component>
          </div>
        </el-tab-pane>
      </el-tabs>
      <el-button type="danger" size="small" icon="el-icon-close" circle @click="close" style="right: 10px;
    position: absolute;
    top: 2px;"></el-button>
      <div class="approval-area" v-show="taskInfo.status === 2 && !taskDetailMode">
        <el-form class="tl-form approval-area" ref="form" label-width="120px">
          <el-row>
            <el-col style="padding-top:10px;text-align: center">
              <el-button :disabled="disabled" :loading="loading" type="primary" @click="syncSonTaskData" v-if="useSyncSonTaskData && editDocInfo">同步子任务单据数据</el-button>
              <el-button :disabled="disabled" :loading="loading" type="success" @click="doComplete(1)" v-if="!recordInfo">{{ isApproval ? buttonNameAgree : buttonNameFinish }}</el-button>
              <el-button :disabled="disabled" :loading="loading" type="danger" @click="dialogVisible = true" v-if="isApproval && !recordInfo">{{ buttonNameNoAgree }}</el-button>
              <el-button :disabled="disabled" :loading="loading" type="warning" @click="openDealBackTask" v-if="isApproval && recordInfo">{{ buttonDealBackTask }}</el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-dialog
      class="back-reason"
      title="任务退回"
      :visible.sync="dialogVisible"
      append-to-body
      width="500px">
      <p style="font-size: 14px">确定要退回当前任务吗？</p>
      <el-form :model="form" v-if="taskInfo.source === 1">
        <el-form-item label="退回原因" prop="approvalopinion" :rules="[{ required: 'true', message: '请输入内容', trigger: 'change' }]" label-width="80px">
          <el-input v-model="form.approvalopinion" type="textarea" :rows="2" placeholder="请输入退回原因" :maxlength="1000" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <template slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doComplete(2)">确 定</el-button>
      </template>
    </el-dialog>
    <labour-task-back ref="openDealBackTask" @refresh="refreshData"></labour-task-back>
  </el-drawer>
</template>

<script>
  import { getAction, putAction, postAction } from '@tapui/utils/http'
  import { TASK_SOURCE, TASK_STATE, TASK_TYPE } from '../../../const/const'
  import LabourTaskBack from './labourTaskBack'
  import labourEdit from './labourEdit'
  export default {
    name: 'TaskExecute',
    components: { LabourTaskBack, labourEdit },
    data() {
      return {
        visible: false,
        title: '任务执行',
        subPage: 'div',
        nodeModel: {},
        recordInfo: null,
        editDocInfo: null,
        isApproval: true,
        disabled: false,
        url: {
          queryNodeInfo: 'cbb/pmTask/queryTaskNodeInfo',
          approvalNodeInfo: 'cbo/approvalNode/load',
          completeTask: 'cbb/pmTask/completeTask', // 完成任务
          backTask: 'cbb/pmTask/backTask', // 退回任务
          backLabourTask: 'cbb/pmTask/backLabourTask', // 退回人工任务
          confirmBackLabourTask: 'cbb/pmTask/confirmBackLabourTask' // 处理退回人工任务
        },
        loading: false,
        beforePassMethod: '',
        beforeBackMethod: '',
        buttonNameAgree: '任务完成',
        buttonNameNoAgree: '任务退回',
        buttonNameFinish: '任务办理',
        buttonDealBackTask: '处理任务退回',
        docWriteInfluence: false,
        docWriteAble: false,
        dialogVisible: false,
        form: {
          approvalopinion: ''
        },
        recordId: null,
        activeName: 'task',
        mainHeight: 100,
        nodeEditable: false,
        outputWInInformation: '',
        reviewWInInformation: '',
        projectInfo: {},
        requisition: '',
        taskDetailMode: false, // 任务详情模式
        editAdvanceTaskAble: false, // 提前编辑任务
        editAdvanceTaskTab: '' // 提前编辑任务tab
      }
    },
    props: {
      taskInfo: {
        type: Object,
        default: () => {
          return {}
        }
      },
      useSyncSonTaskData: {
        default: false
      }
    },
    methods: {
      loadData() {
        getAction(this.url.queryNodeInfo, { nodeid: this.taskInfo.nodeid, taskid: this.taskInfo.id }).then((res) => {
          if (res.success) {
            this.nodeModel = res.result.nodeModel
            this.recordInfo = res.result.recordInfo
            this.editDocInfo = res.result.editDocInfo
            this.bindData()
          } else {
            this.disabled = true
            this.$tap.alert(res.message)
          }
        })
      },
      loadNodeData() {
        getAction(this.url.approvalNodeInfo, { id: this.taskInfo.nodeid }).then((res) => {
          if (res.success) {
            this.nodeModel = res.result
            const page = () => import('@/views/' + this.nodeModel.approvalform)
            this.subPage = page
          } else {
            this.disabled = true
            this.$tap.alert(res.message)
          }
        })
      },
      bindData() {
        if (this.nodeModel.approvalparam) {
          let jsonParam = JSON.parse(this.nodeModel.approvalparam)
          if (jsonParam.hasOwnProperty('isapproval')) {
            this.isApproval = jsonParam.isapproval.toString() === '1'
          } else {
            this.isApproval = true
          }
          if (jsonParam.hasOwnProperty('docwriteable')) {
            this.docWriteAble = true
          }
          if (jsonParam.hasOwnProperty('editable')) {
            if (jsonParam.editable) {
              this.nodeEditable = true
            }
          }
          // 审批通过前，执行编辑页面中的某个方法，等待方法返回成功后才执行审批
          if (jsonParam.hasOwnProperty('beforePassMethod')) {
            this.beforePassMethod = jsonParam.beforePassMethod
          } else {
            this.beforePassMethod = ''
          }
          // 审批驳回前，执行编辑页面中的某个方法，等待方法返回成功后才执行审批
          if (jsonParam.hasOwnProperty('beforeBackMethod')) {
            this.beforeBackMethod = jsonParam.beforeBackMethod
          } else {
            this.beforeBackMethod = ''
          }
          // 同意按钮的显示名字
          if (jsonParam.hasOwnProperty('buttonNameAgree')) {
            this.buttonNameAgree = jsonParam.buttonNameAgree.toString()
          }
          // 不同意按钮的显示名字
          if (jsonParam.hasOwnProperty('buttonNameNoAgree')) {
            this.buttonNameNoAgree = jsonParam.buttonNameNoAgree.toString()
          }
          // 办理按钮的显示名字
          if (jsonParam.hasOwnProperty('buttonNameFinish')) {
            this.buttonNameFinish = jsonParam.buttonNameFinish.toString()
          }
          // 输出产品信息结点
          if (jsonParam.hasOwnProperty('outputWInInformation')) {
            this.outputWInInformation = jsonParam.outputWInInformation.toString()
          } else {
            this.outputWInInformation = '0'
          }
          // 产品信息复核节点
          if (jsonParam.hasOwnProperty('reviewWInInformation')) {
            this.reviewWInInformation = jsonParam.reviewWInInformation.toString()
          } else {
            this.reviewWInInformation = '0'
          }
          // 采购需求处理节点
          if (jsonParam.hasOwnProperty('requisition')) {
            this.requisition = jsonParam.requisition.toString() === '1'
          } else {
            this.requisition = false
          }
          // 额外添加的参数
          if (jsonParam.hasOwnProperty('extraParam')) {
            this.extraParam = jsonParam.extraParam.toString()
          } else {
            this.extraParam = ''
          }
        } else {
          this.isApproval = true
          this.beforePassMethod = ''
          this.beforeBackMethod = ''
          this.outputWInInformation = '0'
          this.reviewWInInformation = '0'
          this.requisition = '0'
          this.extraParam = ''
        }
        const page = () => import('@/views/' + this.nodeModel.approvalform)
        this.subPage = page
      },
      pageCreated() {
        this.$refs.subPage.fromTaskExecute = true
        // 纯查看详情
        if (this.taskDetailMode) {
          this.$refs.subPage.isAdd = false
          this.$refs.subPage.editAdvanceTaskAble = this.editAdvanceTaskAble
          this.$refs.subPage.editAdvanceTaskTab = this.editAdvanceTaskTab
          this.$refs.subPage.openFromTask = true
          this.$refs.subPage.disableEditSubmit = true
          this.$refs.subPage.visible = true
          this.$refs.subPage.projectUUCode = this.taskInfo.projectuucode
          if (this.nodeModel.approvalparam) {
            this.$refs.subPage.nodeParam = JSON.parse(this.nodeModel.approvalparam)
          }
          this.$refs.subPage.open()
          return
        }
        let approvalparamobject = {}
        if (this.nodeModel.approvalparam) {
          approvalparamobject = JSON.parse(this.nodeModel.approvalparam)
          this.$refs.subPage.approvalparamobject = approvalparamobject
        }
        this.$refs.subPage.openFromTask = true
        this.$refs.subPage.projectUUCode = this.taskInfo.projectuucode
        if (this.taskInfo.status === TASK_STATE.Running) {
          this.$refs.subPage.isApproving = true
          this.$refs.subPage.nodeInsId = this.taskInfo.nodeinsid
        }
        this.$refs.subPage.isAdd = false
        this.$refs.subPage.visible = true
        // 来源流程的任务的可以进行编辑单机
        if (this.taskInfo.source === TASK_SOURCE.Flow && this.taskInfo.status === TASK_STATE.Running) {
          this.$refs.subPage.disableEditSubmit = false
        } else if (this.taskInfo.source === TASK_SOURCE.Artificial && this.taskInfo.type === TASK_TYPE.SPECIAL && this.taskInfo.parentcode !== '0' && this.taskInfo.status === TASK_STATE.Running) {
          // 如果是人工，特殊任务，且不同级
          this.$refs.subPage.disableEditSubmit = false
        } else {
          this.$refs.subPage.disableEditSubmit = true
        }
        // 任务信息
        this.$refs.subPage.taskInfoModel = this.taskInfo
        // 是否为子任务编辑权限
        this.$refs.subPage.isSonTaskEdit = this.taskInfo.parentcode && this.docWriteAble
        // 是否可以同步子任务数据
        this.$refs.subPage.syncSonTaskInfo = this.editDocInfo && this.docWriteAble
        // 其他参数
        this.$refs.subPage.outputWInInformation = this.outputWInInformation
        this.$refs.subPage.reviewWInInformation = this.reviewWInInformation
        this.$refs.subPage.requisition = this.requisition
        this.$refs.subPage.extraParam = this.extraParam
        // 如果任务是进行中
        this.$refs.subPage.open()
      },
      doComplete(executeType) {
        if (executeType === 2 && this.taskInfo.source === TASK_SOURCE.Artificial && this.form.approvalopinion.length === 0) {
          this.$tap.alert('请填写退回原因')
          return
        }
        // 是任务节点需要编辑且是图书任务校验标签页是否是编辑的标签页
        if (this.taskInfo.type === TASK_TYPE.SPECIAL && this.nodeEditable) {
          let compareTabRes = this.$refs.subPage.compareTab(this.activeName === 'task')
          if (compareTabRes) {
            this.$tap.alert(compareTabRes)
            return
          }
        }
        this.dialogVisible = false
        this.loading = true
        // 如果是特殊任务，且要填写的走beforePassMethod
        if (this.beforePassMethod.length > 0 && executeType === 1 && this.nodeEditable && this.taskInfo.type === TASK_TYPE.SPECIAL) {
          let method = new Promise(this.$refs.subPage[this.beforePassMethod])
          method
            .then((_) => {
              this.executeTask(executeType)
            })
            .catch((err) => {
              if (err) {
                this.$tap.alert(err, 'warning')
              }
              this.loading = false
            })
        } else if (this.beforeBackMethod.length > 0 && executeType === 2 && this.taskInfo.source === TASK_SOURCE.Flow) {
          let method = new Promise(this.$refs.subPage[this.beforeBackMethod])
          method
            .then((_) => {
              this.executeTask(executeType)
            })
            .catch((err) => {
              if (err) {
                this.$tap.alert(err, 'warning')
              }
              this.loading = false
            })
        } else {
          this.executeTask(executeType)
        }
      },
      executeTask(executeType) {
        let postData = {
          taskid: this.taskInfo.id,
          taskcode: this.taskInfo.code
        }
        let url = ''
        if (executeType === 1) {
          // 通过、办理
          url = this.url.completeTask
        } else if (executeType === 2) {
          // 不通过
          if (this.taskInfo.source === TASK_SOURCE.Artificial) {
            // 人工任务退回
            url = this.url.backLabourTask
          } else {
            // 流程任务退回
            url = this.url.backTask
          }
        }
        postAction(url, postData)
          .then((res) => {
            if (res.success) {
              this.$tap.message('操作成功', 'success')
              this.$emit('refresh')
              this.visible = false
            } else {
              this.$tap.alert(res.message)
            }
            this.loading = false
          })
          .catch((_) => {
            this.loading = false
          })
      },
      open() {
        this.activeName = 'task'
        this.resizeHandler()
        this.form.approvalopinion = ''
        if (this.taskDetailMode) {
          this.loadNodeData()
          return
        }
        this.loadData()
      },
      close() {
        this.taskDetailMode = false
        this.visible = false
        this.taskDetailMode = false // 任务详情模式
        this.editAdvanceTaskAble = false // 提前编辑任务
        this.editAdvanceTaskTab = '' // 提前编辑任务tab
        // this.$emit('cancel')
      },
      refreshData() {
        this.visible = false
      },
      openDealBackTask() {
        this.$refs.openDealBackTask.id = this.recordInfo.id
        this.$refs.openDealBackTask.visible = true
      },
      resizeHandler() {
        this.mainHeight = document.body.getBoundingClientRect().height
        // if (this.taskDetailMode) {
        //   this.mainHeight = document.body.getBoundingClientRect().height
        // } else {
        //   this.mainHeight = document.body.getBoundingClientRect().height - 130
        // }
      },
      taskCreated() {
        if (this.$refs.taskInfoRef) {
          this.$refs.taskInfoRef.id = this.taskInfo.id
          this.$refs.taskInfoRef.disableEditSubmit = true
          this.$refs.taskInfoRef.queryData(this.taskInfo.id)
        }
      },
      syncSonTaskData() {
        this.$refs.subPage.syncSonTaskData(this.editDocInfo)
      }
    },
    created() {
      // 抽屉组件必有
      window.addEventListener('resize', this.resizeHandler)
      this.$once('hook:beforeDestroy', () => {
        // 抽屉组件必有
        window.removeEventListener('resize', this.resizeHandler)
      })
    },
    mounted() {
      this.resizeHandler()
    }
  }
</script>

<style scoped>
  .approval-container {
    background-color: #ffffff;
  }
  .approval-container .approval-area {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    margin-bottom: 0;
    background-color: #fdf6ec;
    border-radius: 5px;
    padding: 5px 0;
    border-top: 1px solid #ccc;
    -webkit-box-shadow: 0 -5px 5px #f2f2f2;
    box-shadow: 0 -5px 5px #f2f2f2;
    overflow: hidden;
    height: 70px;
  }
  .back-reason /deep/ .el-dialog__header {
    display: none;
  }
  .back-reason /deep/ .el-dialog__body {
    padding-top: 10px;
    padding-bottom: 0;
  }
  .approval-container .form-main-area {
    padding: 0!important;
  }
  /deep/ .el-tabs__nav {
    margin-left: 20px;
  }
  .approval-tabs /deep/ .el-tabs__header {
    margin-bottom: 0;
  }
  .approval-tabs /deep/ #pane-task {
    margin-top: 10px;
  }
</style>

